package jalus.blog;

import jalus.Action;
import jalus.FMConfigureFactory;
import jalus.pojo.Collection;
import jalus.service.ConfigureService;
import jalus.service.DoubanService;
import jalus.service.PostService;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jdom.JDOMException;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import freemarker.template.Template;
import freemarker.template.TemplateException;

public class DoubanServlet extends Action {
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) 
			throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		String uri = req.getRequestURI();
		String category = req.getParameter("category");
		String status = req.getParameter("status");
		
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("focustab", "douban");
		root.put("config", ConfigureService.getInstance());
		root.put("spinpostlist", PostService.getInstance().getSpinPostList());
		root.put("userService", userService);
		root.put("uri", uri);
		Template template = null;
		if(StringUtils.isEmpty(category) && StringUtils.isEmpty(status)){
			try {
				template = home(root);
			} catch (JDOMException e) {
				throw new IOException(e);
			}
		}		
		//Template template;
		
        resp.setCharacterEncoding("utf-8"); 
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = resp.getWriter();
        try {
        	template.process(root, out);
		} catch (TemplateException e) {
			e.printStackTrace();
		}
        out.flush();
	}

	private Template home(Map<String, Object> root) 
			throws IOException, JDOMException {
		Template template = FMConfigureFactory.getFMConfigure().getTemplate("doubanHome.html");
		DoubanService doubanService = DoubanService.getInstance();
		Collection movieCollection = doubanService.getCollectionEntryList("movie", null, null, 0, 15);
		Collection bookCollection = doubanService.getCollectionEntryList("book", null, null, 0, 15);
		Collection musicCollection = doubanService.getCollectionEntryList("music", null, null, 0, 15);
		root.put("movieCollection", movieCollection);
		root.put("bookCollection", bookCollection);
		root.put("musicCollection", musicCollection);
		return template;
	}
	
}
